package com.mchsdk.paysdk.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mchsdk.open.ApiCallback;
import com.mchsdk.paysdk.bean.FlagControl;
import com.mchsdk.paysdk.bean.MCPayModel;
import com.mchsdk.paysdk.bean.PersonalCenterModel;
import com.mchsdk.paysdk.bean.pay.ZfbBuPtbEvent;
import com.mchsdk.paysdk.bean.pay.ZfbPay;
import com.mchsdk.paysdk.callback.WFTWapPayCallback;
import com.mchsdk.paysdk.common.Constant;
import com.mchsdk.paysdk.dialog.MCTipDialog;
import com.mchsdk.paysdk.entity.ChannelAndGameinfo;
import com.mchsdk.paysdk.entity.GamePayTypeEntity;
import com.mchsdk.paysdk.entity.WXOrderInfo;
import com.mchsdk.paysdk.http.process.PayTypeProcess;
import com.mchsdk.paysdk.http.process.UserInfoProcess;
import com.mchsdk.paysdk.http.process.WFTOrderInfoProcess;
import com.mchsdk.paysdk.testwatch.PtbNumWatcher;
import com.mchsdk.paysdk.utils.DeviceInfo;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.MCMoneyUtils;
import com.mchsdk.paysdk.utils.ToastUtil;

@SuppressLint("HandlerLeak")
public class MCAddPtbMoneyActivity extends MCBaseActivity {

    private static final String TAG = "MCAddPtbMoneyActivity";

    //    private final int PAYTYPE_PTB = 0x00;
    private final int PAYTYPE_WX = 0x01;
    private final int PAYTYPE_ZFB = 0x02;
//    private final int PAYTYPE_HFB = 0x04;
    /**
     * 付款类型
     */
    private int payType = PAYTYPE_ZFB;
    /**
     * 人民币
     */
    private float rmb;
    /**
     * 提示框
     */
    MCTipDialog mcTipDialog;
    Context context;

    private TextView txtPayRmb;     // 支付人民币
    private EditText txtAccount;    //账号

    private LinearLayout llWXPay;
    private LinearLayout llZFBPay;
    private ImageButton imgbtnSelWX;
    private ImageButton imgbtnSelZFB;
    private Button btnAddPtb;
    /**
     * 或取支付方式
     */
    private final Handler payTypeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.GAME_PAY_TYPE_SUCCESS:
                    handlerGamePayType((GamePayTypeEntity) msg.obj);
                    break;
                case Constant.GAME_PAY_TYPE_FAIL:
                    MCLog.w(TAG, "获取支付方式失败！" + (String) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    private final Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.GET_USER_INFO_SUCCESS:
                    handlerUserInfo(msg.obj);
                    break;
                case Constant.GET_USER_INFO_FAIL:
                    String tip = (String) msg.obj;
                    show(tip);
                    finish();
                    break;
                case Constant.WFT_ORDERINFO_SUCCESS:
                    dismisDialog();
                    boolean isWxAvaliable = DeviceInfo.isWeixinAvilible(context);
                    if (!isWxAvaliable) {
                        ToastUtil.show(context, "没有安装微信");
                        FlagControl.flag = true;
                        return;
                    }
                    WXOrderInfo wxOrderInfo= (WXOrderInfo) msg.obj;
                    Intent intent = new Intent(context, MCWapPayActivity.class);
                    intent.putExtra("WXOrderInfo", wxOrderInfo);
                    context.startActivity(intent);
                    break;
                case Constant.WFT_ORDERINFO_FAIL:
                    dismisDialog();
                    show("支付失败:" + msg.obj);
                    FlagControl.flag = true;
                    break;
                default:
                    break;
            }
            dismisDialog();
        }
    };

    protected void handlerUserPtb() {
        String oldPtb = PersonalCenterModel.getInstance().getUserPtb();
        float ptbOld = Float.parseFloat(oldPtb);
        PersonalCenterModel.getInstance().channelAndGame.setPlatformMoney(rmb
                + ptbOld);
        MCLog.w(TAG, "rmb = " + rmb + ", ptbOld = " + ptbOld);
        show("更新平台币成功");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout("activity_mch_add_platform_money"));
        context = this;
        rmb = 0;
        initTitleView();
        initView();
        initData();
        initPay();
    }

    //加载支付列表
    private void initPay() {
        btnAddPtb.setVisibility(View.GONE);
        PayTypeProcess payTypeProcess = new PayTypeProcess();
        payTypeProcess.post(payTypeHandler);
    }

    private void handlerGamePayType(GamePayTypeEntity gamePayType) {

        if (null != gamePayType) {
            MCLog.w(TAG, gamePayType.toString());
            int selectType = -1;
            selectType = gamePayType.isHaveWX() ? PAYTYPE_WX : selectType;
            selectType = gamePayType.isHaveZFB() ? PAYTYPE_ZFB : selectType;
            if (-1 != selectType) {
                btnAddPtb.setVisibility(View.VISIBLE);
            }

            llZFBPay.setVisibility(gamePayType.isHaveZFB() ? View.VISIBLE : View.GONE);
            llWXPay.setVisibility(gamePayType.isHaveWX() ? View.VISIBLE : View.GONE);
            selectPayType(selectType);
        }
    }


    private void initData() {
        txtAccount.setText(PersonalCenterModel.getInstance().getAccount());
    }

    /**
     * 处理查询的用户信息
     */
    protected void handlerUserInfo(Object obj) {
        ChannelAndGameinfo info = (ChannelAndGameinfo) obj;
        if (null != info) {
            addUserPtb();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initTitleView() {
        TextView txtTitle = (TextView) findViewById(getId("tv_mch_header_title"));
        txtTitle.setGravity(Gravity.CENTER | Gravity.CENTER_VERTICAL);
        txtTitle.setText("平台币充值");
        ImageView ivBack = (ImageView) findViewById(getId("iv_mch_header_back"));
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(backClick);
    }

    private void initView() {
        txtAccount = (EditText) findViewById(getId("edt_mch_account"));

        btnAddPtb = (Button) findViewById(getId("btn_mch_addptb"));
        btnAddPtb.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                checkAccount();
            }
        });

        txtPayRmb = (TextView) findViewById(getId("txt_mch_pay_rmb"));
        txtPayRmb.setText("0");
        //充值数量EditText
        EditText edtPtbNum = (EditText) findViewById(getId("edt_mch_ptb_number"));
        edtPtbNum.addTextChangedListener(new PtbNumWatcher(txtPayRmb, btnAddPtb, edtPtbNum));

        llZFBPay = (LinearLayout) findViewById(getId("ll_mch_addptb_zfb"));
        llZFBPay.setTag(PAYTYPE_ZFB);
        llZFBPay.setOnClickListener(selectPayListener);
        imgbtnSelZFB = (ImageButton) findViewById(getId("imgbtn_mch_sel_zfb"));
        imgbtnSelZFB.setTag(PAYTYPE_ZFB);
        imgbtnSelZFB.setOnClickListener(selectPayListener);

        llWXPay = (LinearLayout) findViewById(getId("ll_mch_addptb_wx"));
        llWXPay.setTag(PAYTYPE_WX);
        llWXPay.setOnClickListener(selectPayListener);
        imgbtnSelWX = (ImageButton) findViewById(getId("imgbtn_mch_sel_wx"));
        imgbtnSelWX.setTag(PAYTYPE_WX);
        imgbtnSelWX.setOnClickListener(selectPayListener);


    }

    private OnClickListener selectPayListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            selectPayType((int) v.getTag());
        }
    };

    /**
     * 检查账号
     */
    protected void checkAccount() {
        String account = txtAccount.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            show("请输入账号");
            return;
        }

        if (PersonalCenterModel.getInstance().getAccount().equals(account)) {
            addUserPtb();
        } else {
            UserInfoProcess userInfoProcess = new UserInfoProcess();
            userInfoProcess.setType("0");
            userInfoProcess.setAccount("");
            userInfoProcess.post(mHandler);
        }
    }

    /**
     * 充值
     */
    private void addUserPtb() {
        rmb = MCMoneyUtils.priceToFloat(txtPayRmb.getText().toString().trim());
        if (rmb != 0) {
            if (FlagControl.flag) {
                addPtb();
                FlagControl.flag = false;
            }
        } else {
            show("请重新输入充值数量");
        }
    }

    protected void addPtb() {
        switch (payType) {
            case PAYTYPE_ZFB:
                submitZfbPay();
                break;
            case PAYTYPE_WX:
                wftPayProcess();
                break;
            default:
                break;
        }
    }

    /**
     * 平台币支付宝充值
     */
    private void submitZfbPay() {
        ZfbPay zfbPay = new ZfbPay((Activity) context);
        zfbPay.zfbPayPTBProcess("平台币", String.format("%.2f", rmb), "平台币充值", zfbBuPtbEvent);
    }

    private ZfbBuPtbEvent zfbBuPtbEvent = new ZfbBuPtbEvent() {
        @Override
        public void buyPTBResult(boolean issuccess) {
            if (issuccess) {
                handlerUserPtb();
            } else {
                MCLog.e(TAG, "购买平台币失败！");
            }
        }
    };

    // TODO 微富通
    private void wftPayProcess() {
        ApiCallback.setWFTWapPayCallback(mWFTWapPayCallback);
        WFTOrderInfoProcess wftProcess = new WFTOrderInfoProcess();
        wftProcess.setGoodsName("平台币");
        wftProcess.setGoodsPrice(String.format("%.2f", rmb));
        wftProcess.setGoodsDesc("平台币充值");
        wftProcess.setExtend("平台币充值");
        wftProcess.setPayType("0");
        wftProcess.post(mHandler);
        showDialog("正在给微信下单..");
    }

    private WFTWapPayCallback mWFTWapPayCallback = new WFTWapPayCallback() {
        @Override
        public void onResult(String code) {
            MCLog.e(TAG, "fun # wftPayCallback code = " + code);
            if (code.equals("0")) {
                sendPayResult(code);
            } else {
                show("支付失败！");
            }
        }
    };




    /**
     * 发送支付结果
     */
    protected void sendPayResult(String payResultCode) {
        MCPayModel.Instance().getPck().callback(payResultCode);
    }

    /**
     * 选择支付方式
     *
     * @param type
     */
    protected void selectPayType(int type) {
        payType = type;
        imgbtnSelZFB.setBackgroundResource(getDrawable("mch_choosepay_3030_uncheck"));
        imgbtnSelWX.setBackgroundResource(getDrawable("mch_choosepay_3030_uncheck"));
        switch (type) {
            case PAYTYPE_ZFB:
                imgbtnSelZFB.setBackgroundResource(getDrawable("mch_choosepay_3030_check"));
                break;
            case PAYTYPE_WX:
                imgbtnSelWX.setBackgroundResource(getDrawable("mch_choosepay_3030_check"));
                break;
            default:
                break;
        }

    }

    /**
     * 退出监听
     */
    OnClickListener backClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            MCAddPtbMoneyActivity.this.finish();
        }
    };


    /**
     * 关闭提示信息
     */
    private void dismisDialog() {
        if (null != mcTipDialog) {
            mcTipDialog.dismiss();
        }
    }

    /**
     * 打开提示信息
     */
    private void showDialog(String message) {
        dismisDialog();
        mcTipDialog = new MCTipDialog.Builder().setMessage(message).show(
                context, ((Activity) context).getFragmentManager());
    }

    /**
     * @param message 吐司内容
     */
    private void show(String message) {
        ToastUtil.show(context, message);
        MCLog.e(TAG, message);
    }
}
